﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;

namespace DG.Common.EF.Reflection
{
    public class ContextConceptualInfosFactory
    {
        private static Dictionary<MetadataWorkspace, ContextConceptualInfos> _cacheEdmxDiscoverFactories;
        public static ContextConceptualInfos GetContextEdmxForContext(DbContext context)
        {
            if (_cacheEdmxDiscoverFactories == null)
                _cacheEdmxDiscoverFactories = new Dictionary<MetadataWorkspace, ContextConceptualInfos>();

            context.Database.Initialize(true);
            var mw = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

            return _cacheEdmxDiscoverFactories.ContainsKey(mw)
                ? _cacheEdmxDiscoverFactories[mw]
                : (_cacheEdmxDiscoverFactories[mw] = new ContextConceptualInfos(context));

        }
        public static ContextConceptualInfos GetContextEdmxForMetadataWorkspace(MetadataWorkspace mw)
        {
            if (_cacheEdmxDiscoverFactories == null)
                _cacheEdmxDiscoverFactories = new Dictionary<MetadataWorkspace, ContextConceptualInfos>();
            
            return _cacheEdmxDiscoverFactories.ContainsKey(mw)
                ? _cacheEdmxDiscoverFactories[mw]
                : (_cacheEdmxDiscoverFactories[mw] = new ContextConceptualInfos(mw));

        }
    }
}